package sdk.webview.fmc.com.fmcsdk.util;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * https管理类
 * Created by zhangjinghao on 2016/12/21 0021.
 */
public class HttpsManager {

    private final static String CLIENT_PRI_KEY = "maike.bks";
    private final static String TRUSTSTORE_PUB_KEY = "truststore.bks";
    private final static String CLIENT_BKS_PASSWORD = "fmc123";
    private final static String TRUSTSTORE_BKS_PASSWORD = "fmc123";
    private final static String KEYSTORE_TYPE = "BKS";
    private final static String PROTOCOL_TYPE = "TLS";
    private final static String CERTIFICATE_FORMAT = "X509";

    private static final Object lock = new Object();
    private static final String TAG = HttpsManager.class.getSimpleName();
    private static SSLContext sslContext;
    private static SSLSocketFactory factory;
    /**
     * 获取Https的证书
     *
     * @param context Activity（fragment）的上下文
     * @return SSL的上下文对象，没有就返回null
     */
    public static SSLContext getSSLContext(Context context) {
        if (sslContext == null) {
            synchronized (lock) {
                sslContext = createSSLContext(context,"eam.crt");
            }
        }
        return sslContext;
    }

    /**
     * 创建Https的证书
     *
     * @param context Activity（fragment）的上下文
     * @param fileName 要打开的assets目录下的文件名
     * @return SSL的上下文对象
     */
    private static SSLContext createSSLContext(Context context, String fileName) {


        SSLContext s_sSLContext;
        CertificateFactory certificateFactory;
        InputStream inputStream = null;
        Certificate cer;
        KeyStore keystore;
        TrustManagerFactory trustManagerFactory;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509","BC");
            //这里导入SSL证书文件
            inputStream = context.getAssets().open(fileName);
            //读取证书
            cer = certificateFactory.generateCertificate(inputStream);
            Log.e(TAG, "cer = " + ((X509Certificate) cer).getSubjectDN());
            //创建一个证书库，并将证书导入证书库
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keystore =  KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null,null); //双向验证时使用
            keystore.setCertificateEntry("trust", cer);
            // 实例化信任库
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            // 初始化信任库
            trustManagerFactory.init(keystore);

            s_sSLContext = SSLContext.getInstance("TLS");
            //[SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2]
            s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            //信任所有证书 （官方不推荐使用）
//			 s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
//				 @Override
//				 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//
//				 }
//
//				 @Override
//				 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//
//				 }
//
//				 @Override
//				 public X509Certificate[] getAcceptedIssuers() {
//					 return null;
//				 }
//			 }}, new SecureRandom());
            return s_sSLContext;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static void setHttpsConnection(HttpURLConnection conn,Context context){
        if (conn instanceof HttpsURLConnection){
            SSLContext sslContext = HttpsManager.getSSLContext(context);
            if (sslContext != null)
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    public static  SSLSocketFactory getSslSocketFactory(Context context) {

        try {

            CertificateFactory cf = CertificateFactory.getInstance("X.509");

            InputStream caInput = context.getAssets().open("eam.crt");

            Certificate ca;

            try {

                ca = cf.generateCertificate(caInput);

            } finally {

                caInput.close();

            }

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            keyStore.load(null, null);

            keyStore.setCertificateEntry("ca", ca);

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");

            sslContext.init(null, tmf.getTrustManagers(), null);

            return sslContext.getSocketFactory();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }


}
